package com.lujieni.springboothutool.utils;

import cn.hutool.core.bean.BeanUtil;
import com.lujieni.springboothutool.po.ParentIdBase;
import com.lujieni.springboothutool.vo.TreeBase;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Athric Yu
 * 2025/3/6
 **/
public class MyTreeUtil {

    /**
     * 转换成多个树
     */
    public static <T extends ParentIdBase, R extends TreeBase<R>> List<R> format(List<T> sources, Class<R> treeBaseType, Function<T, Boolean> parentPredicate) {
        List<T> rootSources = sources.stream().filter(parentPredicate::apply).collect(Collectors.toList());
        List<R> results = new ArrayList<>();
        for (T root : rootSources) {
            R parent = BeanUtil.toBean(root, treeBaseType);
            formatChildren(parent, treeBaseType, sources);
            results.add(parent);
        }
        return results;
    }


    private static <T extends ParentIdBase, R extends TreeBase<R>> void formatChildren(R root, Class<R> treeBaseType, List<T> sources) {
        root.setChildren(new ArrayList<>());
        List<T> filterSources = sources.stream().filter(source -> source.getParentId().equals(root.getId())).sorted(Comparator.comparing(T::getSort)).collect(Collectors.toList());
        for (T filterSource : filterSources) {
            R treeBase = BeanUtil.toBean(filterSource, treeBaseType);
            root.getChildren().add(treeBase);
        }
    }
}
